#include "pagesource.h"

pageSource::pageSource(QWidget *parent) : QWidget(parent)
{
    sourceIsActive = false;

    setStyleSheet(".QLabel{font-size:12px;color:lightgray;min-height:2px;min-width:30px;}"
                  ".QPushButton{font-size:12px;color:lightgray;min-height:25px;min-width:50px;}"
                  //".QComboBox{font-size:12px;color:black;min-height:30px;min-width:50px;}"
                  );

    linkToHardware = new serialConnection;
    connect(linkToHardware->serPort,SIGNAL(readyRead()),this,SLOT(readData()));

    btnB = new QPushButton("基波配置");
    btnB->setFixedSize(100,30);
    btnB->setStyleSheet("color:gray; font-size:15px;");
    btnH = new QPushButton("谐波配置");
    btnH->setFixedSize(100,30);
    btnH->setStyleSheet("color:gray; font-size:15px;");

    enableInternalSrc = new QCheckBox("使用功率源");
    enableInternalSrc->setFixedHeight(30);
    enableInternalSrc->setStyleSheet("color:gray; font-size:20px;");
    enableInternalSrc->setChecked(true);
    enableInternalSrc->setVisible(false);

    widgetB = new widgetBasewave(this);
//    connect(widgetB, SIGNAL(cmdSend()), this, SLOT(sendCmd2Src()));
    widgetH = new widgetHarmonic(this);
    connect(widgetH, SIGNAL(cmdSend()), this, SLOT(sendCmd2Src()));

    connect(btnB, SIGNAL(clicked(bool)), this, SLOT(toggleStackedWidget()));
    connect(btnH, SIGNAL(clicked(bool)), this , SLOT(toggleStackedWidget()));

    QHBoxLayout *layoutBtn = new QHBoxLayout;
    layoutBtn->setContentsMargins(10,0,0,0);
    layoutBtn->addWidget(enableInternalSrc);
//    layoutBtn->addStretch(1);
    layoutBtn->addWidget(btnB);
    layoutBtn->setSpacing(10);
    layoutBtn->addWidget(btnH);
    layoutBtn->addStretch(1);

    widgetMain = new QStackedWidget;
    //widgetMain->setFixedSize(1280,350);
    widgetMain->addWidget(widgetB);
    widgetMain->addWidget(widgetH);
//    widgetMain->setStyleSheet("background-color:red");

    QVBoxLayout *layoutMain = new QVBoxLayout;
    layoutMain->setContentsMargins(0,0,0,0);
    layoutMain->setSpacing(0);
    layoutMain->addLayout(layoutBtn);
    layoutMain->addWidget(widgetMain);
    layoutMain->addStretch(1);

    setLayout(layoutMain);

    QPalette p = palette();
    p.setColor(QPalette::Background,QColor(18,29,34));
    widgetMain->setPalette(p);

    btnB->click();
}

pageSource::~pageSource()
{
    delete linkToHardware;
}

void pageSource::sendCmd2Src()
{
    if(!linkToHardware->serPort->isOpen())
    {
        qDebug()<<"main, sendCmd: no connection to hardware!";

        QWidget* theSender = (QWidget*)sender();

//        if(theSender == widgetB)
//        {
//            QByteArray errStr;
//            errStr[0]=0xff;
//            errStr.append(linkToHardware->serPort->errorString());
//            widgetB->recvResult(errStr);
//        }

        if(theSender == widgetH)
        {
            QByteArray errStr;
            errStr[0]=0xff;
            errStr.append(linkToHardware->serPort->errorString());
            widgetH->recvResult(errStr);
        }
    }
    else
    {
        QWidget* theSender = (QWidget*)sender();

//        if(theSender == widgetB)
//        {
//            qDebug()<<"send"<<widgetB->sendBuf.toHex();
//            sendData(widgetB->sendBuf);
//        }

        if(theSender == widgetH)
        {
            sendData(widgetH->sendBuf);
        }
    }
}

void pageSource::toggleStackedWidget()
{
    QPushButton *btnClicked = (QPushButton *)sender();

    if(btnClicked == btnB)
    {
        widgetMain->setCurrentIndex(0);
        btnB->setStyleSheet("color:yellow; font-size:15px;");
        btnH->setStyleSheet("color:gray; font-size:15px;");
    }

    if(btnClicked == btnH)
    {
        widgetMain->setCurrentIndex(1);
        btnH->setStyleSheet("color:yellow; font-size:15px;");
        btnB->setStyleSheet("color:gray; font-size:15px;");
    }
}

void pageSource::sendData(QByteArray sendBuf)
{
     qDebug()<<"we send"<<sendBuf.toHex();

    linkToHardware->serPort->write(sendBuf);
}

void pageSource::readData()
{
    static QByteArray rcvBuf;

    static int length = 0;

    QByteArray cmd;

    rcvBuf.append(linkToHardware->serPort->readAll());

    qDebug()<<"new data, in buffer: "<<rcvBuf.toHex();

    if(rcvBuf.size() < 2) return; //头、数据长度（1个字节）

    if(length == 0)
    {
        // the right string: 0x23 0xaa cmd length[high] length[low] ...
        while( (0xAA != (unsigned char)rcvBuf[0])
               && (0xAB != (unsigned char)rcvBuf[0]))
        {
            rcvBuf = rcvBuf.mid(1);
            if (rcvBuf.length() == 0) return;
        }

        length = rcvBuf[1];
        qDebug()<<"The data length is"<<length;
    }

    if(rcvBuf.size() < (length+2)) return;

    cmd = rcvBuf.left(length+2);

    qDebug()<<"Result data cmd:"<<cmd.toHex();

    if((unsigned char)cmd[0] == 0xAA)
    {
        widgetB->recvResult(cmd);
    }
    else if((unsigned char)cmd[0] == 0xAB)
    {
        widgetH->recvResult(cmd);
    }

    rcvBuf  = rcvBuf.mid(length + 2);

    rcvBuf.clear();

    length = 0;
}

void pageSource::startSrc()
{
    sourceIsActive = true;

    widgetB->startTest();

    if(!linkToHardware->serPort->isOpen())
    {
        qDebug()<<"main, sendCmd: no connection to hardware!";

        QByteArray errStr;
        errStr[0]=0xff;
        errStr.append(linkToHardware->serPort->errorString());
        widgetB->recvResult(errStr);
    }
    else
    {
        sendData(widgetB->sendBuf);
    }

    qDebug()<<"source up!";
}

void pageSource::stopSrc()
{
    sourceIsActive = false;

    widgetB->sendStopData();

    if(!linkToHardware->serPort->isOpen())
    {
        qDebug()<<"main, sendCmd: no connection to hardware!";

        QByteArray errStr;
        errStr[0]=0xff;
        errStr.append(linkToHardware->serPort->errorString());
        widgetB->recvResult(errStr);
    }
    else
    {
        sendData(widgetB->sendBuf);
    }

    qDebug()<<"source down!";
}

void pageSource::feedback(QByteArray cmd)
{
    sendData(cmd);
}
